package com.cheung.leetcode.arr;

import java.util.HashMap;
import java.util.Map;

public class LC904 {

    public static int totalFruit(int[] fruits) {
        int max = 0;
        int left = 0, right = 0;
        Map<Integer, Integer> count = new HashMap<>();
        for (right = 0; right < fruits.length; right++) {
            // 使用map集合计数
            count.put(fruits[right], count.getOrDefault(fruits[right], 0) + 1);
            while (count.size() > 2) {
                count.put(fruits[left], count.get(fruits[left]) - 1);
                if (count.get(fruits[left]) == 0) {
                    count.remove(fruits[left]);
                }
                left++;
            }
            max = Math.max(max, right - left + 1);
        }
        return max;
    }

    public static void main(String[] args) {
        int[] fruits = {0, 0, 0, 0, 0, 0, 0, 0};
        System.out.println(totalFruit(fruits));
    }
}
